package com.sharemarking.wa.platform.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.Page;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.eum.OrderStateEum;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.common.entity.*;
import com.sharemarking.wa.common.eum.OrderOperateTypeEum;
import com.sharemarking.wa.platform.dto.orderDispatch.DriverListDto;
import com.sharemarking.wa.platform.dto.orderDispatch.OrderInfoDto;
import com.sharemarking.wa.platform.dto.orderDispatch.OrderListDto;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sharemarking.wa.common.SysHttpStatus.REQUIRED_PARAMS_ERROR;

/**
 * @author dxy
 */
@Service
public class OrderDispatchService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private OrgMemberMapper orgMemberMapper;
    @Autowired
    private OrderDispatchMapper orderDispatchMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DriverVerifyMapper driverVerifyMapper;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private OrgCarMapper orgCarMapper;

    public ResponseParams<?> getDriverList() throws Exception {
        Integer memberId = ss.getCurrentUserId();

        int pageIndex = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageIndex")) ? "1" : request.getParameter("pageIndex"));
        int pageSize = Integer.parseInt(StringUtils.isEmpty(request.getParameter("pageSize")) ? "10" : request.getParameter("pageSize"));

        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", (pageIndex - 1) * pageSize);
        params.put("pageSize", pageSize);
        params.put("memberId", memberId);

        List<DriverListDto> list = orderDispatchMapper.getDriverList(params);

        for (DriverListDto d : list) {
            d.setOrderNumber(orderDispatchMapper.getDriverOrderNumber(d.getDriverId()));
        }
        return ResponseParams.ok(new Page<>(list, pageIndex, pageSize, orderDispatchMapper.getDriverListTotal(params), list.size() == pageSize));

    }

    public ResponseParams<?> cancelOrder() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }

        //验证订单
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code).eq("transport_org_member_id",memberId));
        if (!order.getState().equals(OrderStateEum.DRIVER_CONFIRM.getKey())) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }
        if (!order.getType().equals(OrderStateEum.END.getKey())) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        order.setUpdateDate(new Date());
        order.setState(OrderStateEum.TRANSPORT_RECEIPT.getKey());
        orderDispatchMapper.cancelOrder(order);

        return ResponseParams.ok(null);
    }

    public ResponseParams<?> assignDriver() throws Exception {
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String driverId = request.getParameter("driverId");
        String arrivalTime = request.getParameter("arrivalTime");
        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        if (StringUtils.isEmpty(driverId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("driverId"));
        }

        Date date;
        try {
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
            date = s.parse(arrivalTime);
        }catch (Exception e){
            throw RequestException.create(ResponseParams.isDataError("时间格式错误"));
        }

        if (ObjectUtils.isEmpty(orgCarMapper.selectCount(new QueryWrapper<OrgCar>().eq("driver_id",driverId)))) {
            throw RequestException.create(ResponseParams.isDataError("请先给该司机分配车辆！"));
        }

        //验证订单
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code));
        if (!order.getState().equals(OrderStateEum.TRANSPORT_RECEIPT.getKey())) {
            throw RequestException.create(ResponseParams.isDataError("该订单已分配过该司机"));
        }
        if (order.getType() != 1) {
            throw RequestException.create(ResponseParams.isDataError("操作异常"));
        }

        if (!ObjectUtils.isEmpty(order.getTransferStart()) && !ObjectUtils.isEmpty(order.getTransferStart())){
            if (!date.before(order.getTransferStart()) && !date.after(order.getTransferStart())){
                throw RequestException.create(ResponseParams.isDataError("时间错误！"));
            }
        }else if (!ObjectUtils.isEmpty(order.getTransferStart()) && ObjectUtils.isEmpty(order.getTransferStart())){
            if (!date.before(order.getTransferStart())){
                throw RequestException.create(ResponseParams.isDataError("时间错误！"));
            }
        }else if (ObjectUtils.isEmpty(order.getTransferStart()) && !ObjectUtils.isEmpty(order.getTransferStart())){
            if (!date.after(order.getTransferStart())){
                throw RequestException.create(ResponseParams.isDataError("时间错误！"));
            }
        }

        //判断司机接单数是否超过5个
        Integer orderNumber = orderDispatchMapper.getDriverOrderNumber(order.getDriverId());
        if (orderNumber == null || orderNumber >=5) {
            throw RequestException.create(ResponseParams.isDataError("分配到该司机的任务数已满"));
        }

        order.setState(OrderStateEum.DRIVER_CONFIRM.getKey());
        order.setDriverId(driverVerifyMapper.getMemberIdByDriverId(Integer.valueOf(driverId)));
        order.setUpdateDate(new Date());
        order.setTransportOrgId(orgMemberMapper.selectOne(new QueryWrapper<OrgMember>().eq("member_id",memberId)).getOrgId());
        order.setTransportOrgMemberId(memberId);
        order.setArrivalTime(date);

        orderDispatchMapper.assignDriver(order);

        return ResponseParams.ok(null);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseParams<?> replaceDriver() throws Exception{
        Integer memberId = ss.getCurrentUserId();
        String code = request.getParameter("code");
        String driverId = request.getParameter("driverId");

        if (StringUtils.isEmpty(code)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("code"));
        }
        if (StringUtils.isEmpty(driverId)) {
            throw RequestException.create(ResponseParams.requiredParamsIsMissing("driverId"));
        }

        //验证订单
        Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("code", code).eq("transport_org_member_id",memberId));
//        if (!order.getState().equals(OrderStateEum.DRIVER_CONFIRM.getKey())) {
//            throw RequestException.create(ResponseParams.isDataError("该订单已有司机接单"));
//        }
        if (order.getType() != 1) {
            throw RequestException.create(ResponseParams.error(REQUIRED_PARAMS_ERROR));
        }

        //判断司机接单数是否超过5个
        Integer orderNumber = orderDispatchMapper.getDriverOrderNumber(Integer.valueOf(driverId));
        if (orderNumber == null || orderNumber >=5) {
            throw RequestException.create(ResponseParams.isDataError("分配到该司机的任务数已满"));
        }

        order.setState(OrderStateEum.DRIVER_CONFIRM.getKey());
        order.setDriverId(Integer.valueOf(driverId));
        order.setUpdateDate(new Date());

        orderDispatchMapper.replaceDriver(order);

        return ResponseParams.ok(null);
    }
}
